package ti.me.musicplayer

import android.Manifest
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.View
import androidx.activity.ComponentActivity
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import ti.me.musicplayer.databinding.ActivityMainBinding
import kotlin.concurrent.thread

class MainActivity : ComponentActivity(), ServiceConnection {
    val TAG = "MusicService"
    var binder: MusicService.MusicBinder? = null


    private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    private val requestAudioPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
        if (isGranted) {
        } else {
            Log.d(TAG, "onRequestPermissionsResult: Permission denied")
        }
    }
    private val requestNotificationPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
        if (isGranted) {
            startNotification()
        } else {
            Log.d(TAG, "Notification permission denied")
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            requestAudioPermissionLauncher.launch(Manifest.permission.READ_MEDIA_AUDIO)
        } else {
            startMusicService()
        }

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
            requestNotificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
        } else {
            startNotification()
        }

        binding.seekBar.setOnSeekBarChangeListener(
            object : android.widget.SeekBar.OnSeekBarChangeListener {
                override fun onProgressChanged(
                    seekBar: android.widget.SeekBar?,
                    progress: Int,
                    fromUser: Boolean
                ) {
                    if (fromUser) {
                        binder?.currentPosition = progress
                    }
                }
                override fun onStartTrackingTouch(seekBar: android.widget.SeekBar?) {}
                override fun onStopTrackingTouch(seekBar: android.widget.SeekBar?) {}
            })
            startNotification()
        }

    fun startMusicService() {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Command, 1)
        startService(intent)
        bindService(intent, this, Context.BIND_AUTO_CREATE)
    }

    fun onPlay(v: View){
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Command, 1)
        startService(intent)
    }
    fun onPause(v: View){
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Command, 2)
        startService(intent)
    }
    fun onStop(v: View){
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Command, 3)
        startService(intent)
    }
    fun onNext(v: View){
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Command, 4)
        startService(intent)
    }
    fun onPrev(v: View){
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Command, 5)
        startService(intent)
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    override fun onDestroy() {
        super.onDestroy()
        stopService(Intent(this, MusicService::class.java))
        unbindService(this)
    }

    override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
        binder = service as MusicService.MusicBinder
        thread {
            while (binder != null) {
                Thread.sleep(1000)
                runOnUiThread {
                    binder?.let {
                        binding.seekBar.progress = it.currentPosition
                        binding.seekBar.max = it.duration
                        binding.textViewMn.text = it.musicName
                        binding.textViewCount.text = "${it.currentIndex + 1}/${it.size}"
                    }
                }
            }
        }
    }

    override fun onServiceDisconnected(p0: ComponentName?) {
        binder = null
    }


    fun startNotification(){
        val Channel_ID = "music channel"
        val Notification_ID = 1
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val builder: Notification.Builder

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(Channel_ID, "Music Channel", NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(channel)
            builder = Notification.Builder(this, Channel_ID)
        } else {
            builder = Notification.Builder(this)
        }

        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_IMMUTABLE)
        val notification = builder
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle("音乐播放器")
            .setContentText(binder?.musicName ?: "未知歌曲")
            .setContentIntent(pendingIntent)  // 设置点击通知后可以回到主界面
            .setAutoCancel(true)    // 点击通知后自动取消
            .build() // 构建通知

        Log.d("Notification", "Creating notification")
        notificationManager.notify(Notification_ID, notification)
        Log.d("Notification", "Notification sent")
    }
}